﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.ComponentModel.Composition
{
    internal class FilteringCompositionService : ICompositionService
    {
        private readonly ICompositionService _service;

        public event EventHandler<FilteringCompositionServiceEventArgs> FilterPart;

        public FilteringCompositionService(ICompositionService service)
        {
            _service = service;
            _service.AddExportedObject<ICompositionService>(this);
            _service.Compose();
        }

        public bool IsCompositionPending
        {
            get { return _service.IsCompositionPending; }
        }

        public bool IsComposing
        {
            get { return _service.IsComposing; }
        }

        public void AddPart(ComposablePart part)
        {
            if (!Filter(part))
            {
                _service.AddPart(part);
            }
        }

        public void Compose()
        {
            _service.Compose();
        }

        public void RemovePart(ComposablePart part)
        {
            if (!Filter(part))
            {
                _service.RemovePart(part);
            }
        }

        public CompositionResult SatisfyImports(ComposablePart composablePart)
        {
            if (!Filter(composablePart))
            {
                return _service.SatisfyImports(composablePart);
            }

            return CompositionResult.SucceededResult;
        }

        private bool Filter(ComposablePart part)
        {
            FilteringCompositionServiceEventArgs e = new FilteringCompositionServiceEventArgs(part);

            if (FilterPart != null)
            {
                FilterPart(this, e);
            }

            return e.Ignore;
        }
    }
}
